const { mpserverless } = getApp()

function mpserver (collection, fun, condition = {}, info = {}, loading = true, loadingText = '加载中') {
  if (loading) {
    wx.showLoading({
      title: loadingText,
      mask: true
    })
  }
  return new Promise((resolve, reject) => {
    mpserverless.db.collection(collection)[fun](condition, info).then(res => {
      if (loading) wx.hideLoading()
      if (res.success) {
        resolve(res)
      } else {
        wx.showToast({
          title: result.errMsg,
          icon: 'error'
        })
        reject(result)
      }
    }, (rej) => {
      if (loading) wx.hideLoading()
      wx.showToast({
        title: '抱歉服务器繁忙',
        icon: 'error'
      })
      reject(rej)
    })
  })
}

/**
 * 通过find获取一组数据
 * @param {String} collection 查询的集合
 * @param {Object} condition 条件
 * @param {Object} info 信息
 */
function getFind (collection, condition = {}, info = {}) {
  return mpserver(collection, 'find', condition, info)
}

/**
 * 通过findOne获取一条数据
 * @param {String} collection 查询的集合
 * @param {Object} condition 条件
 * @param {Object} info 信息
 */
function getFindOne (collection, condition = {}, info = {}) {
  return mpserver(collection, 'findOne', condition, info)
}


/**
 * 
 * @param {String} collection 查询的集合
 * @param {Object} data 插入数据
 */
function addInsertOne(collection, data = {}) {
  return mpserver(collection, 'insertOne', data)
}

module.exports = {
  getFindOne,
  getFind,
  addInsertOne
}